package com.chen.upload;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.chen.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;


/**
 * 博客信息控制器
 *
 */
@Api(tags = "博客信息模块")
@RestController
@RequestMapping("/upload11")
public class BlogInfoController {

    @Value("${server.port}")
    private String port;

    @Value("${server.ip}")
    private String ip;

        @PostMapping("/uploadFile")
        public Result<String> uploadFile(HttpServletRequest request, HttpServletRequest response, HttpSession session) throws IOException {
            MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile("image");//file是form-data中二进制字段对应的name


            String flag = IdUtil.fastSimpleUUID();//定义文件唯一标识
            String originalFilename = multipartFile.getOriginalFilename();  //获取文件名称
            String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + originalFilename; //获取building-service文件夹路径+文件路径
            //将前台传过来的file对象写入到（磁盘）文件夹中
            File file = FileUtil.writeBytes(multipartFile.getBytes(), rootFilePath);


            //MultipartFile自带的解析方法
            multipartFile.transferTo(file);
            String url="http://"+ip+":"+8081+ "/blog/files/" + flag;
//            String url="http://"+ip+":"+port+"/files/" + flag;

            //返回图片所在url
            return   Result.success(url);
        }


}
